package com.zxf.appliction.controller;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zxf.appliction.domain.Article;
import com.zxf.appliction.domain.BootStrapPage;
import com.zxf.appliction.domain.Content;
import com.zxf.appliction.domain.Filesup;
import com.zxf.appliction.domain.Params;
import com.zxf.appliction.domain.Review;
import com.zxf.appliction.domain.Staffvo;
import com.zxf.appliction.domain.Users;
import com.zxf.appliction.service.ArticleService;
import com.zxf.appliction.service.FileService;
import com.zxf.appliction.service.ReviewService;
import com.zxf.appliction.service.UserService;
import com.zxf.appliction.util.DateJsonValueProcessor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("/indexs")
public class IndexsController {

	@Autowired
	private ArticleService articleService;

	@Autowired
	private UserService userService;
	
	@Autowired
	private FileService fileService;
	
	@Autowired
	private ReviewService reviewService;

	private static Logger logger = Logger.getLogger(IndexsController.class);
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	public String login() {
		return "login";
	}

	/**
	 * 博客首页信息
	 * @param params
	 * @param author
	 * @param searchText
	 * @param title
	 * @param article
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/index")
	public @ResponseBody
	ModelAndView index(Params params, String author,String searchText, String title, Article article, HttpServletRequest request,
			HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		params.setPagesize(5);
		String key = "3";
		Users user = userService.getUsers(key);
		
		//首页幻灯片文章列表
		List<Article> slideArticlelist = articleService.getArticleListBytop(5);
		//首页热门推荐文章列表
		List<Article> hotArticlelist = articleService.getArticleListBytop(10);
		
		List<Article> articlelist = articleService.getArticleListByPagesizeAndPage(params, searchText);
		List<Review> hotreviewlist = reviewService.gethotReviewList(10);
		logger.info("articlelist:" + articlelist);
		int totalPages = articleService.getArtcleTotleByPagesizeAndPage(params, searchText);
        int nexPage = params.getPage() + 1;
        int prePage = params.getPage() - 1;
        
		ModelAndView modelAndView = new ModelAndView("base");
		modelAndView.addObject("hotArticlelist", hotArticlelist);
		modelAndView.addObject("hotreviewlist", hotreviewlist);
		modelAndView.addObject("slideArticlelist", slideArticlelist);
		modelAndView.addObject("articlelist", articlelist);
		modelAndView.addObject("user", user);
		modelAndView.addObject("totalPages", totalPages);
		modelAndView.addObject("curPage", params.getPage());
		modelAndView.addObject("nexPage", nexPage);
		modelAndView.addObject("prePage", prePage);
		
		logger.info("totalPages:" + totalPages +" curPage:" + params.getPage() + " nexPage" + nexPage + " prePage" + prePage+" slideArticlelist:"+slideArticlelist+" hotArticlelist:" + hotArticlelist);
		long endTime = System.currentTimeMillis();
		logger.info("耗时:"+(endTime - startTime));
		return modelAndView;

	}


	// 用户登录
	@RequestMapping("/userlogin")
	public @ResponseBody
	Map<String, Object> userlogin(Users users, HttpServletRequest request,
			HttpServletResponse response) {
		 Map<String,Object> responseMap = new HashMap<String,Object>();  
		HttpSession session = request.getSession();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		Users users2 ;
		// 得到生成的验证码
		String strCode = (String) session.getAttribute("randomCode");
		logger.info("验证码：" + strCode);
		

		 users2 = userService.selectusers(users);

		if (null != users2) {
			 responseMap.put("method", "userlogin");  
		        responseMap.put("success", "true");  
		        responseMap.put("message", "登录成功！"); 
		        session.setAttribute("userInfo", users2);

		} else {
			responseMap.put("success", "false");  
	        responseMap.put("message", "用户名或者密码错误！");

		}
        logger.info("用户登录：" + users2);
       
        return responseMap; 

	}

	
	/**
	 * 查看 文章信息
	 * @param articleID
	 * @param title
	 * @param request 
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/detailarticle")
	public ModelAndView detailarticle(String articleID, String title,
			HttpServletRequest request, HttpServletResponse response) {

		int artid = 0;

		Article article ;
		Content content ;
		String key = "3";
		Users user = userService.getUsers(key);
		if (StringUtils.isNotBlank(articleID) && StringUtils.isNotEmpty(articleID))
			artid = Integer.parseInt(articleID);
		// 首页热门推荐文章列表
		List<Article> hotArticlelist = articleService.getArticleListBytop(10);
		// 取的文章信息
		List<Review> reviewlist = reviewService.getReviewList(artid);
		article = articleService.detailarticle(artid);

		content = articleService.detailcontent(artid);

		if (null != content) {
			article.setContent(content.getContent());
		}

		logger.info("article: " + article);

		ModelAndView modelAndView = new ModelAndView("post_detail");

		modelAndView.addObject("article", article);
		modelAndView.addObject("reviewlist", reviewlist);
		modelAndView.addObject("hotArticlelist", hotArticlelist);
		modelAndView.addObject("user", user);

		return modelAndView;
	}

	// 文章列表
	@RequestMapping(value = "/articlelist", method = RequestMethod.POST)
	public @ResponseBody
	JSONObject userlist(Params params, String searchText, String startime, String limit, String offset, String endtime,
			String channelid, Article article, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		int limits = 0;
		int start = 0;
		int channelID = 0;
		if (null != limit && limit != "")
			limits = Integer.parseInt(limit);
		if (null != offset && offset != "" && offset != "0")
			start = Integer.parseInt(offset);
		if (null != channelid && channelid != "") {
			channelID = Integer.parseInt(channelid);
			article.setChannelid(channelID);

		}

		try {
			if (null != startime && !"".equals(startime)) {
				params.setStartdate(sdf.parse(startime));
			}
			if (null != endtime && !"".equals(endtime)) {
				params.setEnddate(sdf.parse(endtime));
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}

		JSONArray js = new JSONArray();
		params.setLimit(limits);
		// 页码
		// 每页数量
		params.setStart(start);
		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		List articlelist = articleService.getArticleList(params, article);
		int totle = articleService.getartcletotle(params, article);
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("rows", js.fromObject(articlelist, jsonConfig));

		obj.put("success", true);

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}

	@RequestMapping(value = "/getarticlelist.do")
	public @ResponseBody
	ModelAndView getarticlelist(HttpServletRequest request,
			HttpServletResponse response) {
		Users user ;
		user = (Users) request.getSession().getAttribute("userInfo");
		ModelAndView modelAndView = new ModelAndView("webshow/index");
		modelAndView.addObject("user", user);

		return modelAndView;

	}

	@RequestMapping(value = { "/redisuserlist" })
	public @ResponseBody
	JSONObject redisuserlist(Params params, BootStrapPage temp, String limit,
			String start, Users users, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		JSONArray js = new JSONArray();
		JsonConfig jsonConfig = new JsonConfig();

		// 每页数量
		int pageSize2 = 0;
		if (null != limit && limit != "") {
			pageSize2 = Integer.parseInt(limit);

		}

		List userlist = userService.getRedisUserList(params.getPage(),
				pageSize2);
		int totle = userService.getRedistotle("users");
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("rows", js.fromObject(userlist, jsonConfig));
		obj.put("success", true);

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}

	// 用户列表
	@RequestMapping("/userlist")
	public @ResponseBody
	JSONObject userlist(Params params, String page, String limit, String start,
			String userid, HttpServletRequest request,
			HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		JSONArray js = new JSONArray();
		JsonConfig jsonConfig = new JsonConfig();
		// 页码
		int pageno = 1;
		pageno = params.getPage();
		// 每页数量
		int pageSize2 = Integer.parseInt(limit);
		int start2 = (pageno - 1) * pageSize2;
		// Map<String, Object> userlist2 = (Map<String, Object>)
		List userlist2 = userService.getUserList3(start2, pageSize2);
		int totle = userService.getusertotle();
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("rows", js.fromObject(userlist2, jsonConfig));
		obj.put("success", true);

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}
	
	/**
	 * 博客首页信息
	 * @param params
	 * @param author
	 * @param searchText
	 * @param title
	 * @param article
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/pictureIndex")
	public @ResponseBody
	ModelAndView pictureIndex(Params params, String author,String searchText, String title, Article article, HttpServletRequest request,
			HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		params.setPagesize(5);
		String key = "3";
		Users user = userService.getUsers(key);
		
		
		//首页热门推荐文章列表
		List<Staffvo> hotFileslist = fileService.getFileListBytop(10);
		
		List<Staffvo> fileslist = fileService.getFileListByPagesizeAndPage(params, searchText);
		List<Review> hotreviewlist = reviewService.gethotReviewList(10);
		logger.info("fileslist:" + fileslist+" hotFileslist:"+hotFileslist);
		int totalPages = fileService.getFileTotleByPagesizeAndPage(params, searchText);
        int nexPage = params.getPage() + 1;
        int prePage = params.getPage() - 1;
        
		ModelAndView modelAndView = new ModelAndView("pictureIndex");
		modelAndView.addObject("hotFileslist", hotFileslist);
		modelAndView.addObject("fileslist", fileslist);
		modelAndView.addObject("user", user);
		modelAndView.addObject("hotreviewlist", hotreviewlist);
		
		modelAndView.addObject("totalPages", totalPages);
		modelAndView.addObject("curPage", params.getPage());
		modelAndView.addObject("nexPage", nexPage);
		modelAndView.addObject("prePage", prePage);
		
		logger.info("totalPages:" + totalPages +" curPage:" + params.getPage() + " nexPage" + nexPage + " prePage" + prePage+" hotArticlelist:" + hotFileslist);
		long endTime = System.currentTimeMillis();
		logger.info("耗时:"+(endTime - startTime));
		return modelAndView;

	}
	
	/**
	 * 博客首页信息
	 * @param params
	 * @param author
	 * @param searchText
	 * @param title
	 * @param article
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getallArticles")
	public @ResponseBody
	ModelAndView getallArticles(Params params, String author,String searchText, String title, Article article, HttpServletRequest request,
			HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		params.setPagesize(10);
		String key = "3";
		Users user = userService.getUsers(key);
		
		
		//首页热门推荐文章列表
		List<Staffvo> hotFileslist = fileService.getFileListBytop(10);
		
		List<Article> articlelist = articleService.getArticleListByPagesizeAndPage(params, searchText);
		List<Review> hotreviewlist = reviewService.gethotReviewList(10);
		logger.info("articlelist:" + articlelist+" hotFileslist:"+hotFileslist);
		int totalPages = articleService.getArtcleTotleByPagesizeAndPage(params, searchText);
        int nexPage = params.getPage() + 1;
        int prePage = params.getPage() - 1;
        
		ModelAndView modelAndView = new ModelAndView("allArticles");
		modelAndView.addObject("hotFileslist", hotFileslist);
		modelAndView.addObject("articlelist", articlelist);
		modelAndView.addObject("user", user);
		modelAndView.addObject("hotreviewlist", hotreviewlist);
		
		modelAndView.addObject("totalPages", totalPages);
		modelAndView.addObject("curPage", params.getPage());
		modelAndView.addObject("nexPage", nexPage);
		modelAndView.addObject("prePage", prePage);
		
		logger.info("totalPages:" + totalPages +" curPage:" + params.getPage() + " nexPage" + nexPage + " prePage" + prePage+" hotArticlelist:" + hotFileslist);
		long endTime = System.currentTimeMillis();
		logger.info("耗时:"+(endTime - startTime));
		return modelAndView;

	}
	
	/**
	 * 查看 文章信息
	 * @param articleID
	 * @param title
	 * @param request 
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/detailPicture")
	public ModelAndView detailPicture(Integer staffid,
			HttpServletRequest request, HttpServletResponse response) {
		
		
		Staffvo staffvo;
		
       List<Filesup> filesupList;
       String key = "3";
		Users user = userService.getUsers(key);

		// 取的图片信息
		staffvo = fileService.detailstaffvo(staffid);
		//首页热门推荐文章列表
		List<Staffvo> hotFileslist = fileService.getFileListBytop(10);
		
		filesupList = fileService.getfilesupListByStaffid(staffid);
		List<Review> hotreviewlist = reviewService.gethotReviewList(10);
		List<Review> reviewlist = reviewService.getReviewList(staffid);
		
		
		logger.info("staffvo: "+staffvo +" filesupList:"+ filesupList);
		
		ModelAndView modelAndView = new ModelAndView("pictureDetail");
		modelAndView.addObject("hotFileslist", hotFileslist);
		modelAndView.addObject("staffvo", staffvo);
		modelAndView.addObject("filesupList", filesupList);
		modelAndView.addObject("reviewlist", reviewlist);
		modelAndView.addObject("hotreviewlist", hotreviewlist);
		modelAndView.addObject("user", user);
		

		return modelAndView;
	}
	
}
